import process from 'node:process'
import { Modal } from 'ant-design-vue'
import { ENV_CONFIG } from '@/config'

// 获取app.js 的哈希值
function getAppHash(scripts: HTMLCollectionOf<HTMLScriptElement>) {
  let localVersion = ''
  for (let i = 0; i < scripts.length; i++) {
    const src = scripts[i].getAttribute('src')
    if (src && src.includes('index-')) {
      // 正则返回中间版本号(如果没有，返回空)
      const regRes = /index-(.*?).js/
      if (regRes.test(src))
        localVersion = regRes.exec(src)![1]
    }
  }
  return localVersion
}

// 获取本地的app.js版本号
function getLocalHash() {
  return getAppHash(document.getElementsByTagName('script'))
}

// 获取线上的app.js版本号
function getLatestHash() {
  return new Promise((resolve, reject) => {
    // 加上时间戳，防止缓存
    fetch(`//${
      window.location.host
    // }${import.meta.env.VITE_PUBLIC_PATH}?_time=${Date.now()}`).then(async (res) => {
    }${(ENV_CONFIG as any)[import.meta.env.MODE].publicPath}?_time=${Date.now()}`).then(async (res) => {
      const html = await res.text()// 转成字符串判断
      const doc = new DOMParser().parseFromString(html, 'text/html')
      const newVersion = getAppHash(doc.getElementsByTagName('script'))
      resolve(newVersion)
    }).catch((err) => {
      reject(err)
    })
  })
}

// 版本比较提示更新
let showModal = false
async function autoUpdate() {
  const localVersion = getLocalHash()
  const newVersion = await getLatestHash()
  if (!showModal && localVersion !== newVersion) {
    showModal = true
    Modal.confirm({
      title: 'Version notifications',
      content: 'A new version has been detected to be available',
      cancelButtonProps: { style: { display: 'none' } },
      okButtonProps: { style: { width: '250px' } },
      okText: 'Refresh',
      width: '350px',
      class: 'version-location',
      async onOk() {
        return await new Promise(() => {
          window.location.reload()
        })
      },
      onCancel() {},
    })
  }
}

// 定时执行(每5分钟检测一次)
const duration = 1000 * 60 * 5
let t: any = null
function checkUpdate() {
  t = setInterval(async () => {
    autoUpdate()
  }, duration)
}

// 在页面关闭前清除定时器
window.addEventListener('beforeunload', () => {
  clearInterval(t)
})

if (process.env.NODE_ENV !== 'development')
  checkUpdate()
